<?php
namespace app\index\controller;

use think\Db;
use think\Log;
use think\Antiaddiction;

class Free
{
    //应用标识（APPID）
    public $appId = '2c842c4588f44f75a67a9bfcd38be173';
    //用户密钥（Secret Key）：
    public $secretKey = '2266316a7e846f961e0c1b0c6c6e4e4b';
    //游戏备案识别码（bizId）
    public $bizId = '1199001695';//骑战三国测试

    public $antiapi = NULL;
    
    public function __construct()
    {
        $this->antiapi = new Antiaddiction();
        $this->antiapi->initialize($this->appId , $this->secretKey , $this->bizId);
    }    
    
	public function is_check()
	{
		$ret = ['code' => 500, 'msg' => '姓名和身份证不一致'];
		if (empty($_POST['name']) || empty($_POST['id_number']) || empty($_POST['sign'])) {
			$ret['msg'] = '参数不完整';
			echo json_encode($ret);
			exit;
		}

		$name = $_POST['name'];
		$id_number = $_POST['id_number'];

		if(!checkName($name)){
			$ret['msg'] = '姓名格式不正确';
			echo json_encode($ret);
			exit;
		}
		if(!action('Checkidcard/checkIdentity',['num'=>$id_number])){
			$ret['msg'] = '身份证格式不正确';
			echo json_encode($ret);
			exit;
		}
		if(!isset($_POST['ip'])||!filter_var($_POST['ip'], FILTER_VALIDATE_IP)||empty($_POST['ip'])){
			$ret['msg'] = 'ip地址有误';
			echo json_encode($ret);
			exit;
		}

		$m_sign = sha1($name . $id_number . 'xGSIWhUhjSwe.');
		if ($m_sign !== $_POST['sign']) {
			$ret['msg'] = 'sign验证失败';
			echo json_encode($ret);
			exit;
		}
		$where['name'] = trim($name);
		$where['id_number'] = trim($id_number);
		$find = Db ::table('tab_id_number')->field('id,name,id_number as idcard,sex,birthday,address,status') -> where($where) -> find();
		if (null == $find) {
			$count = Db ::table('tab_record') -> where('ip', $_POST['ip']) -> count();
			if ($count >= 5 && !in_array($_POST['ip'],['58.218.102.42'])) {
				$ret['msg'] = '实名认证最多只能验证5次  请联系客服协助';
				echo json_encode($ret);
				exit;
			}
			$ai = md5($this->appId .$id_number);
			$url_path = 'https://api.wlc.nppa.gov.cn/idcard/authentication/check';
			$data =  ['ai'=>$ai,'name'=>$name,'idNum'=>$id_number];
			$xx = $this->antiapi->api_post($url_path,$data);
			file_put_contents(dirname(__FILE__).'/1.txt',json_encode($xx));
			
			////$xx['data']['result']['status'] 0：认证成功 1：认证中 2：认证失败
			$add_record['name'] = $name;
			$add_record['id_number'] = $id_number;
			$add_record['ip'] = $_POST['ip'];
			$add_record['create_time'] = time();
			Db ::table('tab_record') -> insert($add_record);
			$idinfo = getIDCardInfo($id_number);
			if ($xx['errcode'] == 0) {
				$add['name'] = $name;
				$add['id_number'] = $id_number;
				$add['birthday'] = $idinfo['birthday'];
				$add['sex'] = $idinfo['sex'];
				$add['pi']  = $xx['data']['result']['pi'];
				$add['status']  = $xx['data']['result']['status'];
				$add['create_time'] = time();
				if (Db ::table('tab_id_number') -> insert($add)) {
					$ret['code'] = 200;
					$ret['msg'] = '验证成功';
				} else {
					$ret['msg'] = '验证成功';
				}
				$ret['data'] = $xx['data']['result'];
				$ret['data']['birthday']=$add['birthday'];
			} else {
				$ret['data'] = $xx['data']['result'];
				$ret['msg'] = $xx['errmsg'];
			}
			$log=new Log();
			$log->record('----接口返回----'.json_encode($ret));
			
			echo json_encode($ret);
			exit;
			
		}elseif ($find['status']!=0){//实名认证查询
		    $ai = md5($this->appId .$id_number);
		    $url_path = 'http://api2.wlc.nppa.gov.cn/idcard/authentication/query';
		    $data =  ['ai'=>$ai];
		    $xx = $this->antiapi->api_get($url_path,$data);
		    file_put_contents(dirname(__FILE__).'/2.txt',json_encode($xx));

		    ////$xx['data']['result']['status'] 0：认证成功 1：认证中 2：认证失败
		    if ($xx['errcode'] == 0) {
		        $add['status'] = $xx['data']['result']['status'];
		        $add['pi']  = $xx['data']['result']['pi'];
		        if (Db ::table('tab_id_number') -> where('id', $find['id'])->save($add)) {
		            $ret['code'] = $add['status'];
		            $ret['msg'] = '验证成功';
		        } else {
		            $ret['msg'] = '验证成功';
		        }
		        $ret['data'] = $xx['data']['result'];
				$ret['data']['birthday'] = $find['birthday'];
		    } else {
		        $ret['data'] = $xx['data']['result'];
		        $ret['msg'] = $xx['errmsg'];
		    }
		    $log=new Log();
		    $log->record('----接口返回----'.json_encode($ret));
		    	
		    echo json_encode($ret);
		    exit;
		} else {
			$ret['code'] = $find['status'];
			$ret['msg'] = '验证成功';
			$ret['data'] = $find;
			
			$log=new Log();
			$log->record('----接口返回----'.json_encode($ret));
			
			echo json_encode($ret);
			exit;
		}
	}
	
	/*游戏行为上报   上线*/
	protected function testcase07()
	{
	    $pi = $_REQUEST['[pi'];
	    $url_path = 'http://api2.wlc.nppa.gov.cn/behavior/collection/loginout';
	    $data = [
	        'collections'=>[
	            [
	                'no'=>1,
	                'si'=> md5($this->appId . $pi),//一个会话标识只能对应唯一的实名用户，一个实名用户可以拥有多个会话标识；同一用户单次游戏会话中，上下线动作必须使用同一会话标识上报备注：会话标识仅标识一次用户会话，生命周期仅为一次上线和与之匹配的一次下线，不会对生命周期之外的任何业务有任何影响
	                'bt'=>0,  ///游戏用户行为类型 0：下线 1：上线
	                'ot'=>time(),
	                'ct'=>2,  ///用户行为数据上报类型 0：已认证通过用户 2：游客用户
	                'di'=>'ecvndx6r6xfwofmufs3lbimcr639r33t',
	                'pi'=>$pi,
	            ]
	        ],
	    ];
	    println(jsonEncode($data));
	    $ret = $this->antiapi->api_post($url_path,$data);
	    println(jsonEncode($ret));
	}
}
